<script lang="ts">
import { useDebounceFn, useLocalStorage } from '@peng_kai/kit/libs/vueuse';
import { GameSwiperContainer } from '~comp-b/game';
import { GameSearchLoading } from '~/composables/useGameLoading';

interface SearchState {
  lastSearchTags: string[];
}
// 历史数据storage
function useSearchLocalStaorage() {
  const state = useLocalStorage<SearchState>('search', { lastSearchTags: [] });
  const showHistory = computed(() => state.value.lastSearchTags.length > 0);
  // 清除历史记录
  function onEliminate() {
    state.value.lastSearchTags = [];
  }

  const newest = computed(() => state.value.lastSearchTags.reverse().slice(0, 10));

  return {
    onEliminate,
    showHistory,
    state,
    newest,
  };
}

// 猜你喜欢接口
function useRecommendQuery() {
  const params = reactive({
    type_code: 'hot',
    page_size: 30,
    page: 1,
  });
  // todo 暂无接口暂时这样写  猜你喜欢接口
  const recommendGameQry = useQuery({
    queryKey: [apis.apiGameList.id, 'recommend'],
    queryFn: () => apis.apiGameList(params),
  });

  const recommendGameList = computed(() => recommendGameQry?.data.value?.list ?? []);

  return {
    recommendGameList,
    recommendGameQry,
  };
};

// 搜索游戏接口
function useSearchGameQuery() {
  const searchGameParams = reactive({
    keyword: '',
    page: 1,
    page_size: 30,
  });
  const enabled = computed(() => !!searchGameParams.keyword);
  // todo 搜索接口
  const searchGameQry = useQuery({
    queryKey: [apis.apiGameList.id, 'searchResult', () => searchGameParams.keyword],
    queryFn: () => apis.apiGameList(searchGameParams),
    enabled,
  });

  const showSearch = computed(() => searchGameQry.isFetched);
  const searchGameList = computed(() => searchGameQry.data.value?.list ?? []);
  return {
    searchGameParams,
    searchGameQry,
    searchGameList,
    showSearch,
  };
}

export const searchPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./GameSearch.vue')),
  { title: computed(() => $t('yaumayCeCeamLBiC9G8Dn')), maskClosable: false, width: 1500, wrapClassName: 'ant-cover__Modal-drawer ant-cover__Modal-search __screen-drawer', centered: true, footer: null, closable: true },
);
</script>

<script setup lang="ts">
const emits = defineEmits<{
  close: [];
}>();

const query = ref('');
const { onEliminate, showHistory, state, newest } = useSearchLocalStaorage();
const { recommendGameQry, recommendGameList } = useRecommendQuery();
const { searchGameParams, searchGameQry, showSearch, searchGameList } = useSearchGameQuery();

const debouncedFn = useDebounceFn(() => {
  if ((query.value.trim()).length >= 3) {
    searchGameParams.keyword = query.value;
    searchGameQry.refetch();
  }
}, 500);

function useHistorySearch(e: string) {
  query.value = e;
  searchGameParams.keyword = e;
  searchGameQry.refetch();
}

function onRegister(item: any) {
  if (item.status === 2)
    return;
  state.value.lastSearchTags.push(item.name);
  setTimeout(() => (emits('close')), 0);
}

function getRandomInt(max: number) {
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - 0 + 1)) + 0;
}

// 随机游戏无封面设计 todo
const randomGame = computed(() => recommendGameList.value[getRandomInt(recommendGameList.value.length - 1)]);
</script>

<template>
  <div class="py-5">
    <!-- 搜索 -->
    <div class="mb-3">
      <AInput v-model:value="query" allowclear clear :placeholder="$t('0eXb9qAmg_2dczf1ay1l1')" @change="debouncedFn">
        <template #prefix>
          <i class="i-local:search text-sys-text-body" />
        </template>
      </AInput>
      <div v-if="query.length < 3" class="mt-3 text-center text-sys-text-body">
        {{ $t('vfdMfYxZnaEnz4G8xnaZ') }}
      </div>
    </div>
    <!-- 搜索结果 -->
    <div v-if="query.length >= 3 && showSearch" class="my-3">
      <div class="flex-between">
        <div class="sub-title">
          <i class="icon i-local:hot-picks" /> <span>{{ $t('cEwzZEbqxyuOtEq9QSoBj') }}</span>
        </div>
        <div>
          <div class="flex-center justify-end gap-2.5 text-2xl">
            <span class="search-result-prev h-8.5 w-6 cursor-pointer">
              <i class="i-ri:arrow-left-s-line text-sys-text-body" />
            </span>
            <span class="search-result-next h-8.5 w-6 cursor-pointer">
              <i class="i-ri:arrow-right-s-line text-sys-text-body" />
            </span>
          </div>
        </div>
      </div>
      <TSuspenseView v-bind="buildSvPropsOfQuery(searchGameQry, { isEmptyFn: (d:any) => !d?.list })">
        <GameSwiperContainer :navigation="{ nextEl: '.search-result-next', prevEl: '.search-result-prev' }" bg="#26272E">
          <swiper-slide v-for="item in searchGameList" :key="item.code" class="py-2" @click="onRegister(item)">
            <TGameCover class="w-full" :detail="item" />
          </swiper-slide>
        </GameSwiperContainer>
        <template #pending>
          <GameSearchLoading />
        </template>
        <template #empty>
          <TEmpty />
        </template>
      </TSuspenseView>
    </div>
    <!-- 历史搜索 -->
    <div v-if="!query && showHistory" class="my-3">
      <div class="sub-title">
        <i class="icon i-local:hot-picks" /> <span>{{ $t('kL0Var1qRZe4WyKbaNn') }} </span>
      </div>
      <div class="search-history text-sm">
        <span v-for="i in newest" :key="i" class="history-search" @click="useHistorySearch(i)">{{ i }}</span>
      </div>
      <div class="text-right">
        <span class="cursor-pointer" @click="onEliminate">{{ $t('zyaElJo08YtUf3UvOcvOs') }}</span>
      </div>
    </div>

    <!-- 猜你喜欢 -->
    <div class="my-3">
      <div class="flex-between">
        <div class="sub-title">
          <i class="icon i-local:hot-picks" /> <span>{{ $t('o3U7K97l1DOa78PBlBxIg') }}</span>
        </div>
        <div>
          <div class="flex-center justify-end gap-2.5 text-2xl">
            <span class="link-prev h-8.5 w-6 cursor-pointer">
              <i class="i-ri:arrow-left-s-line text-sys-text-body" />
            </span>
            <span class="link-next h-8.5 w-6 cursor-pointer">
              <i class="i-ri:arrow-right-s-line text-sys-text-body" />
            </span>
          </div>
        </div>
      </div>
      <TSuspenseView v-bind="buildSvPropsOfQuery(recommendGameQry)">
        <GameSwiperContainer :navigation="{ nextEl: '.link-next', prevEl: '.link-prev' }" bg="#26272E">
          <!-- <swiper-slide class="py-2" @click="message.info('随机游戏，暂无设计')"> -->
          <!--  <TGameCover class="w-full" :detail="randomGame" /> -->
          <!-- </swiper-slide> -->
          <swiper-slide v-for="item in recommendGameList" :key="item.code" class="py-2" @click="onRegister(item)">
            <TGameCover class="w-full" :detail="item" />
          </swiper-slide>
        </GameSwiperContainer>

        <template #pending>
          <GameSearchLoading />
        </template>
      </TSuspenseView>
    </div>
  </div>
</template>

<style scoped lang="scss">
.sub-title {
  --uno: 'flex-center justify-start gap-2 text-4';
}
.history-search {
  --uno: 'inline-block cursor-pointer rounded bg-#32343F px-4 text-sys-text-body leading-5 m1';
}
.ant-modal-wrap.ant-cover__Modal-search {
  --uno: '!bg-#1D1E24';
}
</style>
